/**
 * ajax请求配置
 */
import axios from 'axios'
import qs from 'qs'
import Router from 'vue-router'
import {Message} from 'element-ui'
import Vue from 'vue'

var AUTH_TOKEN = (function () {
  return sessionStorage.getItem("sessionId");
})();

let vm = new Vue();
/*
var oldRequest = axios.Axios.prototype.request;

axios.Axios.prototype.request = function request(config) {
    var self = this;
    return new Promise(function (resolve, reject) {
        oldRequest.call(self, config).then(
            function (response) {
                if (response.data && response.data.casError == '403' && response.data.redirect) {
                    console.log('原始请求- 发现 CAS 客户端未登录');
                    let url = response.data.redirect + "&method=POST";
                    axios.get(url, {
                        withCredentials: true,
                        responseType: 'document',
                    }).then(function (ssoResponse) {
                        var form = ssoResponse.data.getElementsByTagName('form');
                        if (form) {
                            form = form[0];
                            if (form.getAttribute('id') === 'fm1') {
                                console.log('获取ticket 失败 ，CAS 服务端未登录');
                                ssoResponse.message = '获取ticket 失败 ，CAS 服务端未登录';
                                reject(ssoResponse);
                                alert('请在弹出窗口完成登录后，再进行操作');
                                window.open(response.data.redirect.substring(0, response.data.redirect.indexOf('?')));
                            }
                            else if (form.getAttribute('name') === 'acsForm' && form.getElementsByTagName('input')) {
                                var join = config.url.indexOf('?') > 0 ? '&' : '?';
                                config.url = config.url + join + 'ticket=' + form.getElementsByTagName('input')[0].value;
                                axios.request(config).then(function (withLoginResponse) {
                                    console.log('获取ticket 成功，再次请求数据');
                                    resolve(withLoginResponse);
                                }).catch(function (err) {
                                    reject(err);
                                });
                            }
                        }
                    })
                } else {
                    resolve(response);
                }
            },
            function (error) {
                //reject(error);
                if(error.response.status==401){
                  console.log('原始请求- 发现 CAS 客户端未登录');
                  sessionStorage.removeItem('user');
                  window.location.href = process.env.API_ROOT+'/login/cas';
                }
            }
        );
    });
};
*/
var instance = axios.create({
  headers: {
    // 'Access-Control-Allow-Origin': '*',
    // 'Content-Type': 'application/json',
    // 'Accept': 'application/json'
    'Content-Type':  'application/json',
    'Access-Control-Allow-Credentials' : 'true',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, PUT, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
  }
});
// axios默认配置
instance.defaults.timeout = 10000;   // 超时时间
instance.defaults.baseURL = process.env.API_ROOT;  // 默认地址
instance.defaults.withCredentials = true;
instance.defaults.crossDomain = true;


// 路由请求拦截
// http request 拦截器
instance.interceptors.request.use(
  config => {
    // console.log(config)
    //config.data = JSON.stringify(config.data);
    //config.headers.lang = vm.prototype.$i18n;
    let url = config.url;
    config.url = url.indexOf('?') == '-1' ? url + '?_=' + new Date().getTime() : url + '&_=' + new Date().getTime();
    if (url.indexOf("login") > -1) {
      //sessionStorage.removeItem('sessionId');
      //sessionStorage.removeItem('user');
      //config.headers.token = "";
    }
    else {
      //config.headers.Authorization =sessionStorage.getItem("sessionId");
      // config.headers.token = sessionStorage.getItem("sessionId");
      // config.headers.jwt = sessionStorage.getItem("sessionId");
    }
    //let abc =this.$cookies.get("sid");
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    // config.headers['Access-Control-Allow-Origin'] = '*';
    // config.headers['Access-Control-Allow-Credentials']='true';
    //判断是否存在ticket，如果存在的话，则每个http header都加上ticket
    // if (this.$cookies.get("token")) {
    //     //用户每次操作，都将cookie设置成2小时
    //     this.$cookies.set("token",this.$cookies.get("token") ,1/12)
    //     this.$cookies.set("name",this.$cookies.get("name") ,1/12)
    //     config.headers.token = this.$cookies.get("token");
    //     config.headers.name= this.$cookies.get("name");
    // }

    return config;
  },
  error => {
    Message.error("test");
    return Promise.resolve(error);
  });

// 路由响应拦截
// http response 拦截器
instance.interceptors.response.use(
  response => {
    // console.log(error)
    if (response.data.code == "401") {
      sessionStorage.removeItem("sessionId");
      sessionStorage.removeItem('user');
      // window.location.href = '/';
      //this.$router.push({path: '/'});
      // Router.replace({path:"/login",query:{redirect:Router.currentRoute.fullPath}});
    }
//             console.log("response.data.resultCode是404")
//             // 返回 错误代码-1 清除ticket信息并跳转到登录页面
// //      cookie.del("ticket")
// //      window.location.href='http://login.com'
//             return response;
//         }else{
//             return response;
//         }
    return response;
  },
  error => {
    console.log(error)
    if (error.response && error.response.status == 401) {
      console.log('原始请求- 发现 CAS 客户端未登录');
      sessionStorage.removeItem('user');
      window.location.href = process.env.API_ROOT + '/login/cas';
      // window.location.href = process.env.API_ROOT + '/oauth2login';
    }
    return Promise.reject(error);   // 返回接口返回的错误信息
  });
export default instance;
